<template>
  <div>
    <div class="logintip">密码登录</div>

    <van-form @submit="onSubmit">
      <van-cell-group inset style="
    margin-top: 45rem;
">
        <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]" />
        <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]" />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit" color="#ff5777">
          登录
        </van-button>
      </div>
    </van-form>
    <div style="margin: 16px; font-size: 14rem">
      <!-- <button class="zhuece" @click="zhuceHandler">注册</button> -->
      <button class="zhuece" @click="goToRegisterPage">注册</button>
    </div>
    <div class="Forgot">
      <router-link to="/forgot" style="color: #999;">忘记密码?</router-link>
    </div>
    <div class="agreement">
      <input type="checkbox" v-model="agreed" />我已阅读并且同意用户协议和隐私协议
    </div>
    <div class="loginbot">请立即登录或注册体验完整版APP哦...</div>
    <div style="height:55rem"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { Toast } from 'vant';
import { useUserStore } from '@/stores/user.ts';
import { useRouter } from 'vue-router'
const router = useRouter(); // 引入路由器实例
const username = ref('');
const password = ref('');
const users = ref(JSON.parse(localStorage.getItem("users")) || []);
const agreed = ref(false); // 新增复选框绑定的变量

const userStore = useUserStore();

// 确保在组件挂载时加载用户数据
onMounted(() => {
  console.log('用户数据已加载：', users.value);
});
// 观察 users 数组的变化并持久化到 localStorage
watch(users, (newUsers) => {
  localStorage.setItem("users", JSON.stringify(newUsers));
}, { deep: true });

// 注册处理函数
// const zhuceHandler = () => {
//   if (!username.value || !password.value) {
//     Toast('请填写用户名和密码');
//     return;
//   }
//   const existingUser = users.value.find(user => user.username === username.value);
//   if (existingUser) {
//     Toast('用户名已存在');
//     return;
//   }
//   users.value.push({ username: username.value, password: password.value });
//   Toast('注册成功,请登录');
//   username.value = '';
//   password.value = '';
// };
const goToRegisterPage = () => {
  router.push('/register');
};

// 检查是否勾选了复选框
const checkAgreement = () => {
  if (!agreed.value) {
    Toast('请勾选用户协议和隐私协议');
    return false;
  }
  return true;
};
// 登录处理函数
const onSubmit = () => {
  if (!checkAgreement()) {
    return; // 如果没有勾选复选框，则阻止表单提交
  }
  const user = users.value.find((item) => item.username === username.value && item.password === password.value);
  setTimeout(() => {
    if (user) {
      Toast('登录成功');
      // 使用 Pinia store 中的方法
      userStore.setToken(user.username);
      // 检查是否存在 target 参数，如果存在则跳转到 target，否则跳转到默认页面（如首页）
      const target = router.currentRoute.value.query.target;
      if (target) {
        router.push({ path: target });
      }
    } else {
      Toast('密码错误或用户不存在');
    }
  }, 1000);

};
</script>

<style lang="less" scoped>
.logintip {
  width: 100%;
  height: 44rem;
  text-align: center;
  margin: 0 0 15rem 0;
  font-size: 20rem;
  line-height: 44rem;
  border-bottom: 1rem solid #d1cdcd;
  color: #999;
}

.loginlogo {
  width: 100%;
  height: 100rem;
  background-color: aliceblue;
  display: flex;
  justify-content: space-between;
}

.zhuece {
  width: 100%;
  border-radius: 999rem;
  background-color: #ff5777;
  border: 1px solid #ff5777;
  color: white;
  position: relative;
  display: inline-block;
  box-sizing: border-box;
  height: 44px;
  margin: 0;
  padding: 0;
  text-align: center;
  cursor: pointer;
  transition: opacity 0.2s;
  -webkit-appearance: none;
  font: inherit;
}

.Forgot {
  color: #999;
  position: absolute;
  right: 20rem;
}

.agreement {
  width: 100%;
  text-align: center;
  margin-top: 200rem;
  font-size: 12rem;
  color: #999;
  justify-content: center;
  align-items: center;
  display: flex;
}

.loginbot {
  width: 100%;
  text-align: center;
  margin-top: 20rem;
  font-size: 14rem;
  color: #999;
}
</style>
